const { MCPServer } = require('@mcp/node');
const fetch = require('node-fetch');

// 初始化MCP服务器
const mcp = new MCPServer('weather');

// 常量
const NWS_API_BASE = 'https://api.weather.gov';
const USER_AGENT = 'weather-app/1.0';

async function makeNWSRequest(url) {
    const headers = {
        'User-Agent': USER_AGENT,
        'Accept': 'application/geo+json'
    };
    try {
        const response = await fetch(url, { headers });
        if (!response.ok) throw new Error('API request failed');
        return await response.json();
    } catch (error) {
        return null;
    }
}

function formatAlert(feature) {
    const props = feature.properties;
    return `
Event: ${props.event || 'Unknown'}
Area: ${props.areaDesc || 'Unknown'}
Severity: ${props.severity || 'Unknown'}
Description: ${props.description || 'No description available'}
Instructions: ${props.instruction || 'No specific instructions provided'}
`;
}

// 获取警报工具
mcp.tool({
    name: 'get-alerts',
    description: '获取美国州的天气警报',
    parameters: {
        state: {
            type: 'string',
            description: '两字母美国州代码（例如CA、NY）'
        }
    },
    async execute({ state }) {
        const url = `${NWS_API_BASE}/alerts/active/area/${state}`;
        const data = await makeNWSRequest(url);

        if (!data || !data.features) {
            return '无法获取警报或未找到警报。';
        }

        if (data.features.length === 0) {
            return '该州没有活动警报。';
        }

        const alerts = data.features.map(formatAlert);
        return alerts.join('\n---\n');
    }
});

// 获取预报工具
mcp.tool({
    name: 'get-forecast',
    description: '获取位置的天气预报',
    parameters: {
        latitude: {
            type: 'number',
            description: '位置的纬度'
        },
        longitude: {
            type: 'number',
            description: '位置的经度'
        }
    },
    async execute({ latitude, longitude }) {
        // 首先获取预报网格端点
        const pointsUrl = `${NWS_API_BASE}/points/${latitude},${longitude}`;
        const pointsData = await makeNWSRequest(pointsUrl);

        if (!pointsData) {
            return '无法为此位置获取预报数据。';
        }

        // 从点响应中获取预报URL
        const forecastUrl = pointsData.properties.forecast;
        const forecastData = await makeNWSRequest(forecastUrl);

        if (!forecastData) {
            return '无法获取详细预报。';
        }

        // 将时段格式化为可读预报
        const periods = forecastData.properties.periods;
        const forecasts = periods.slice(0, 5).map(period => `
${period.name}:
Temperature: ${period.temperature}°${period.temperatureUnit}
Wind: ${period.windSpeed} ${period.windDirection}
Forecast: ${period.detailedForecast}
`);

        return forecasts.join('\n---\n');
    }
});

mcp.start();
